import { defineStore } from "pinia";
import { useUserStore } from "./user";

/** 全局弹窗枚举 */
export enum GlobalModalEnum {
  CONFIRM,
}

export const useGlobalModalStore = defineStore("GLOBAL_MODAL", () => {
  const userStore = useUserStore();

  // 弹窗id
  let modalId = 0;

  /** 是否登录 */
  const isLogin = computed(() => userStore.isLogin);

  /**
   * 全局弹窗列表-单例
   */
  const singleModalList = ref<
    {
      id: number;
      show: boolean;
      key: GlobalModalEnum;
    }[]
  >([]);

  /**
   * 全局弹窗列表-多例 attrs 包含 onCancel, onConfirm
   */
  const multipleModalList = ref<
    {
      id: number;
      show: boolean;
      needLogin: boolean;
      key: GlobalModalEnum;
      attrs: Record<string, any>;
      /** 更新 */
      update: (attrs: Record<string, any>) => void;
      /** 注销 */
      destroy: () => void;
      /** 切换展示状态 */
      switchShow: (status: boolean) => void;
    }[]
  >([]);

  const state = reactive({
    singleModalList,
    multipleModalList,
  });

  /**
   * 需要登录的多例弹窗列表
   */
  const needLoginMultipleModalList = computed(() => {
    return multipleModalList.value.filter((item) => item.needLogin);
  });

  /**
   * 创建单例弹窗 ！！！不对外暴露
   */
  function createSingle(key: GlobalModalEnum, status: boolean): void {
    const target = {
      id: modalId++,
      show: status,
      key,
    };
    singleModalList.value.push(target);
  }

  /**
   * 打开单例弹窗
   */
  function openSingle(key: GlobalModalEnum) {
    const target = singleModalList.value.find((item) => item.key === key);
    if (target) {
      target.show = true;
    } else {
      createSingle(key, true);
    }
  }

  /**
   * 切换单例弹窗
   */
  function switchSingle(key: GlobalModalEnum, status: boolean) {
    const target = singleModalList.value.find((item) => item.key === key);
    if (target) {
      target.show = status;
    } else {
      createSingle(key, status);
    }
  }

  /**
   * 销毁单例弹窗
   */
  function destroySingle(key: GlobalModalEnum) {
    const index = singleModalList.value.findIndex((item) => item.key === key);
    if (index > -1) {
      singleModalList.value.splice(index, 1);
    }
  }

  /**
   * 创建多例弹窗
   */
  function createMultiple(
    key: GlobalModalEnum,
    options: {
      __NEED_LOGIN__?: boolean;
      [key: string]: any;
    },
  ) {
    const { __NEED_LOGIN__: needLogin = false, ...attrs } = options;
    const target = {
      id: modalId++,
      show: needLogin ? isLogin.value : true,
      key,
      attrs,
      needLogin,
      update: (attrs: Record<string, any>) => {
        const targetReactive = multipleModalList.value.find(
          (item) => item.id === target.id,
        );

        if (targetReactive) {
          targetReactive.attrs = {
            ...target.attrs,
            ...attrs,
          };
        } else {
          console.warn(`多例弹窗${key}已被销毁`);
        }
      },
      destroy: () => {
        const index = multipleModalList.value.findIndex(
          (item) => item.id === target.id,
        );
        if (index === -1) {
          return console.warn(`多例弹窗${key}已被销毁`);
        }

        multipleModalList.value[index].show = false;

        // 动画结束后销毁
        setTimeout(() => {
          // 确认定时器到时间后 是否还在列表中
          const i = multipleModalList.value.findIndex(
            (item) => item.id === target.id,
          );
          if (i > -1) {
            multipleModalList.value.splice(i, 1);
          }
        }, 300);
      },
      switchShow: (status: boolean) => {
        const targetReactive = multipleModalList.value.find(
          (item) => item.id === target.id,
        );

        if (targetReactive) {
          targetReactive.show = status;
        } else {
          console.warn(`多例弹窗${key}已被销毁`);
        }
      },
    };
    multipleModalList.value.push(target);
    return {
      update: target.update,
      destroy: target.destroy,
      switchShow: target.switchShow,
    };
  }

  watch(
    [needLoginMultipleModalList, isLogin],
    ([n1, n2]) => {
      if (!n2) {
        n1.forEach((item) => {
          item.destroy();
        });
      }
    },
    {
      immediate: true,
    },
  );

  return {
    state,
    openSingle,
    switchSingle,
    destroySingle,
    createMultiple,
  };
});
